package com.tyao.note.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.tyao.framework.core.JsonResult;
import com.tyao.note.model.BAccessory;
import com.tyao.note.model.BFolder;
import com.tyao.note.service.AccessoryService;
import com.tyao.note.service.FolderService;
import com.tyao.utils.FileOperate;

@Controller
public class AccessoryController extends BaseController{

	@Autowired
	private AccessoryService accessoryService;
	
	@Autowired
	private FolderService folderService;

	@RequestMapping("/note/upload")
	public String uploadFile() {
		return "/uploadTest";
	}
	@RequestMapping("/note/fileMove")
	public String moveFile(HttpServletRequest request) {
		String id=request.getParameter("id");
		BAccessory acc= accessoryService.getAccById(Long.parseLong(id));
		request.setAttribute("acc", acc);
		return "/file-move";
	}
	
	@RequestMapping("/note/fileMoveSubmit")
	@ResponseBody
	public JsonResult moveSubmit(HttpServletRequest request) {
		JsonResult result = new JsonResult();
		String folderId=request.getParameter("fileId");
		String newFolderId=request.getParameter("newFolderId");
		BAccessory acc=accessoryService.getAccById(Long.parseLong(folderId));
		if(acc.getFolderId()!=Long.parseLong(newFolderId)) {
			//文件根目录
			String basePath=folderService.getRootPath();
			//文件原路径
			String oldPath=folderService.getFolderPathById(acc.getFolderId())+"/"+acc.getAccName();
			//文件新路径
			String newPath=folderService.getFolderPathById(Long.parseLong(newFolderId))+"/"+acc.getAccName();
			File newFile=new File(basePath+newPath);
			if(newFile.exists()){
				result.setSuccess(false);
				result.setMsg("文件重名，请修改后再移动文件！");
			}else {
				//移动磁盘上文件
				boolean isMove=FileOperate.moveFile(basePath+oldPath, basePath+newPath);
				if(isMove) {
					//修改表中记录
					 int flag= accessoryService.updateFolderId(Long.parseLong(folderId), Long.parseLong(newFolderId));
					if(flag>0) {
						result.setSuccess(true);
					}else {
						result.setSuccess(false);
						result.setMsg("文件移动更新失败！");
					}	
				}else {
					result.setSuccess(false);
					result.setMsg("文件移动失败！");
				}				
			}			
		}		
		 return result;
	}
	
	// 检查是否重名，如果重名自动后面加(1)、(2)
	public String checkRename(String path, String fileName, int i, String constantName) {
		String strName = fileName;
		String extName = fileName.substring(fileName.lastIndexOf(".") + 1);
		File newFile = new File(path +"/"+ fileName);
		if (newFile.exists()) {
			strName = constantName + "(" + i + ")." + extName;
			i++;
			strName = checkRename(path, strName, i, constantName);
		}
		return strName;
	}

	@RequestMapping("/note/fileUpload")
	@ResponseBody
	public JsonResult notes(@RequestParam(value = "fileUpload", required = false) MultipartFile[] multipartFiles,
			HttpServletRequest request, HttpSession session) throws Exception, IOException{ 
		JsonResult result = new JsonResult();
		String folderIdStr=request.getParameter("folderId1");
		Long folderId=0l;
		if("".equals(folderIdStr)) {
			List<BFolder> folders=	folderService.getAllFolderByUserId(getId(session));
			for(BFolder folder:folders) {
				if(folder.getFolderName().equals(getUserName(session))) {
					folderId=folder.getId();
					break;
				}
			}
		}else {
			folderId=Long.parseLong(folderIdStr);
		}
		String basePath=folderService.getRootPath();
		String filePath=folderService.getFolderPathById(folderId);
		String path = basePath+filePath;
		File dir = new File(path);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		String fjname = "";
		float fileSize = 0;
		if (multipartFiles != null && multipartFiles.length > 0) {
			for (MultipartFile multipartFile : multipartFiles) {
				if (multipartFile.getSize() == 0) {
					continue;
				}
				// 文件大小
				fileSize = multipartFile.getSize();
				// 文件类型
				String contentType = multipartFile.getContentType();
				// 文件全名称
				fjname = multipartFile.getOriginalFilename();
				// 文件后缀
				String fjhz = fjname.substring(fjname.lastIndexOf(".") + 1);
				// 不含后缀的文件名称 
				String shortName = fjname.substring(0, fjname.lastIndexOf("."));
				// 处理文件重名问题
				fjname = checkRename(path, fjname, 1, shortName);
				// 文件保存路径
				String savePath = path+'/'+fjname;
				// 转存文件
				multipartFile.transferTo(new File(savePath));
				// 存入附件表
				accessoryService.saveAcc(fjname,filePath, fjhz, fileSize, folderId, getId(session));
			}
			// result.setData(list);
		}
		result.setMsg("上传成功");
		result.setSuccess(true);
		return result;
	}
	@RequestMapping("/note/fileDown")
	@ResponseBody
	public void down(HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException,IOException {
		String fileId=request.getParameter("id");
		//String folderId=request.getParameter("folderId");
		BAccessory acc=new BAccessory();
		//下载的附件信息
		acc=accessoryService.getAccById(Long.parseLong(fileId));
		String fileName=acc.getAccName();
		//根路径
		String basePath=folderService.getRootPath();
		//下载的文件夹路径
		String filePath=folderService.getFolderPathById(acc.getFolderId());
		//下载的完整路径
		String path = basePath+filePath+'/';
		//得到要下载的文件
		File file = new File(path + "\\" + fileName);
		response.setCharacterEncoding("UTF-8");
		//设置ContentType字段值
		response.setContentType("text/html;charset=utf-8");
		//如果文件不存在
		if(!file.exists()){
			response.getWriter().write("<script language='javascript'>alert('该文件不存在！');history.back(-1)</script>");
		    return;
		 }
		
		//通知浏览器以下载的方式打开
		response.addHeader("Content-type", "appllication/octet-stream");
		response.addHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(fileName,"UTF-8"));
		//读取要下载的文件，保存到文件输入流
		FileInputStream in = new FileInputStream(path +  fileName);
		//通知文件流读取文件
		//InputStream in = getServletContext().getResourceAsStream(path+filename);
		//获取response对象的输出流
		OutputStream out = response.getOutputStream();
		byte[] buffer = new byte[1024];
		int len;
		//循环取出流中的数据
		while((len = in.read(buffer)) != -1){
				out.write(buffer,0,len);
			}
		 //关闭文件输入流
		in.close();
		//关闭输出流
		out.close();
	}
	/**
	 * 文件删除，可以删除多个
	 * @param accIds
	 * @return
	 */
	@RequestMapping("/note/filesDel")
	@ResponseBody
	public JsonResult filesDelete(String accIds){
		JsonResult result = new JsonResult();
		int flag= accessoryService.accDelete(accIds);
		if(flag>0) {
			result.setSuccess(true);
			result.setMsg("删除成功");
			result.setData(flag);
		}else {
			result.setSuccess(false);
			result.setMsg("删除失败");
			result.setData(flag);
		}
		return result;
	}
	/**
	 * 获取文件列表
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping("/note/fileList")
	@ResponseBody
	public JsonResult noteFiles(HttpServletRequest request,HttpSession session) {
		JsonResult result = new JsonResult();
		String folderId=request.getParameter("folderId");
		String beginTime=request.getParameter("logmin");
		String endTime=request.getParameter("logmax");
		String fileName=request.getParameter("fileName");
		List<BAccessory> acc=accessoryService.getAccBySearch(folderId, fileName, beginTime, endTime,getId(session));
		result.setData(acc);
		result.setSuccess(true);
		result.setMsg("");
		return result;
	}
	
	@RequestMapping("/test")
	@ResponseBody
	public String test() {
		Long folderId=(long) 80;
		List<BAccessory> acc=accessoryService.getAccByFolder(folderId);
		String fileSize= convertFileSize(acc.get(0).getAccSize());
		return fileSize;
	}
	/**
	 * 文件大小byte转换单位（B、KB、MB、GB）
	 * @param size
	 * @return
	 */
	public static String convertFileSize(float size) {
		long kb = 1024;
        long mb = kb * 1024;
        long gb = mb * 1024;
 
        if (size >= gb) {
            return String.format("%.1f GB", (float) size / gb);
        } else if (size >= mb) {
            float f = (float) size / mb;
            return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f);
        } else if (size >= kb) {
            float f = (float) size / kb;
            return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f);
        } else
            return String.format("%d B", size);
	}
}
